package service

import (
	"gin-bms/global"
	"gin-bms/model"
)

func CreateRoleMenu(menus []model.SysMenu, roleId string) (err error) {
	var role model.SysRole
	role.RoleId = roleId
	role.SysMenus = menus
	err = SetRoleMenu(&role)
	return err
}

//获取动态菜单树
func GetRoleMenuTree(roleId string) (err error, roleMenus []model.SysRoleMenu) {
	err, menuTree := getRoleMenuTreeMap(roleId)
	roleMenus = menuTree["0"]
	for i := 0; i < len(roleMenus); i++ {
		err = getRoleMenuChildrenList(&roleMenus[i], menuTree)
	}
	return err, roleMenus
}

//私有：获取路由树
func getRoleMenuTreeMap(roleId string) (err error, treeMap map[string][]model.SysRoleMenu) {
	var roleMenus []model.SysRoleMenu
	treeMap = make(map[string][]model.SysRoleMenu)
	err = global.GLOBAL_DB.Where("role_id = ?", roleId).Order("sort").Preload("Parameters").Find(&roleMenus).Error
	for _, v := range roleMenus {
		treeMap[v.ParentId] = append(treeMap[v.ParentId], v)
	}
	return err, treeMap
}

//私有：获取路由子菜单
func getRoleMenuChildrenList(roleMenu *model.SysRoleMenu, treeMap map[string][]model.SysRoleMenu) (err error) {
	roleMenu.Children = treeMap[roleMenu.MenuId]
	for i := 0; i < len(roleMenu.Children); i++ {
		err = getRoleMenuChildrenList(&roleMenu.Children[i], treeMap)
	}
	return err
}
